package com.asdf.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.TitledBorder;

public class AgreementDialog extends Dialog
{

	private static final long	serialVersionUID	= - 3085483517487037685L;
	
	private JEditorPane licenseText = new JEditorPane( );
	private JPanel 		buttonPanel = new JPanel( new FlowLayout( FlowLayout.CENTER));
	private JButton 	btnAgree	= new JButton( "Agree");
	private JButton 	btnNotAgree	= new JButton( "Don't agree");
	
	private String 		licenseFileName;
	
	public AgreementDialog( String fileName)
	{
		super( "Agreement dialog");
		licenseFileName = fileName;
		drawLabelsAndInputs( );
		pack( );
	}

	protected void drawLabelsAndInputs( )
	{
		licenseText.setEditable( false);
		JScrollPane editorScrollPane = new JScrollPane( licenseText);
		editorScrollPane.setVerticalScrollBarPolicy(
		                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

		BufferedReader bufferedInput = null;
		StringBuffer buffer          = new StringBuffer( );
		int ch;
		try
		{
			bufferedInput = new BufferedReader( new FileReader( licenseFileName));
			
			while ( (ch = bufferedInput.read( ))!=-1)
				buffer.append( (char)ch);
			
			licenseText.setText( buffer.toString( ));
			editorScrollPane.setPreferredSize( new Dimension( 450, 150));
			
			TitledBorder title = BorderFactory.createTitledBorder( BorderFactory.createLineBorder(Color.black),
					  "Please, read the service lincese agreement", TitledBorder.LEFT, TitledBorder.TOP);

			editorScrollPane.setBorder( title);
			
			buttonPanel.add( btnAgree);
			buttonPanel.add( btnNotAgree);
			
			add( editorScrollPane);
			add( buttonPanel);
		}
		catch ( IOException e)
		{
			e.printStackTrace( );
		}
		finally
		{
			if ( bufferedInput != null)
				try
				{
					bufferedInput.close( );
				}
				catch ( IOException e)
				{
				}
		}
	}
	
	public void registerEventHandlerAgreeCommand( String commandName, ActionListener listener)
	{
		btnAgree.setActionCommand( commandName);
		btnAgree.addActionListener( listener);
	}
	
	public void registerEventHandlerNotAgreeCommand( String commandName, ActionListener listener)
	{
		btnNotAgree.setActionCommand( commandName);
		btnNotAgree.addActionListener( listener);
	}
	
	public static void main( String [ ] args)
	{
		AgreementDialog dialog = new AgreementDialog( "src/com/asdf/ui/Dialog.java");
		dialog.setVisible( true);
	}
}
